package cn.niit.letuseatdemo.interceptor;


import cn.niit.letuseatdemo.common.Constants;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Description
 * @Author Zhang Shiqi
 * @CreateTime 2022/10/11 8:46
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {

    /**
    * @Description: 控制器方法执行前执行
    * @Author: Zhang Shiqi
    * @CreateTime： 2022/10/11 8:50
     * @param: request
     * @param: response
     * @param: handler
     * @return: boolean  true是放行，flase拦截
    **/

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String URI = request.getRequestURI();
        System.out.println("LoginInterceptor.preHandle----------------"+URI);
        Object obj=request.getSession().getAttribute(Constants.ADMIN_SESSION_USER_KEY);
        Object object=request.getSession().getAttribute(Constants.ADMIN_SESSION_STORE_KEY);
        //如果请求路径以/admin开头，且session中没有登录用户信息，则拦截
        if ((URI.startsWith("/admin") || URI.equals("/") || URI.equals("/index") ) && null == obj && object == null){
            System.out.println("当前用户没有登录，请重新登录。。。。");
            request.getSession().setAttribute("errorMsg","登录失效！请重新登录");
            response.sendRedirect("/admin/login");
            return false;
        }
        //如果请求路径以/store开头，且session中没有登录用户信息，则拦截
        if ((URI.startsWith("/store") || URI.equals("/") || URI.equals("/index") ) && null == obj && object == null){
            System.out.println("当前用户没有登录，请重新登录。。。。");
            request.getSession().setAttribute("errorMsg","登录失效！请重新登录");
            response.sendRedirect("/store/login");
            return false;
        }


        //return false;//一片空白,拒绝，拦截成功
        return true; //放行，继续执行控制器方法，则正常显示页面
    }


    /*
     * @Description: 控制器方法执行后执行
     * 主要用于渲染公共数据，例如菜单等信息
     * @Author: Zhang Shiqi
     * @CreateTime： 2022/10/11 8:51
     * @param: request
     * @param: response
     * @param: handler
     * @param: modelAndView
     **/
    @Override

    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("LoginInterceptor.postHandle----------------");

    }

    /*
     * @Description: 输出提示
     * @Author: Zhang Shiqi
     * @CreateTime： 2022/10/11 8:52
     * @param: request
     * @param: response
     * @param: handler
     * @param: ex
     **/
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("LoginInterceptor.afterCompition----------------");

    }
}
